package com.suishoupai.xmb.entity;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import java.util.UUID;


/**
 * 回复给七牛的消息格式
 * 
 * @author caojian
 * @version 1.0.0
 */
public final class AjaxQiniuMessage {
	private String key;// 指定的资源名（上传策略开启callbackFetchKey后由服务器指定key）
	private AjaxMessage payload;// 返回给上传端的数据

	public static AjaxQiniuMessage newSuccess(String key, AjaxMessage payload) {
		return new AjaxQiniuMessage(key, payload);
	}

	public static AjaxQiniuMessage newError(AjaxMessage payload) {
		return new AjaxQiniuMessage(getErrorKey(), payload);
	}

	/**
	 * 
	 * @param key
	 *            资源名
	 * @param payload
	 *            返回给上传端的内容
	 */
	private AjaxQiniuMessage(String key, AjaxMessage payload) {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("key不能为空" + key);
		}
		if (payload == null) {
			throw new IllegalArgumentException("payload不能为空");
		}
		this.key = key;
		this.payload = payload;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		if (StringUtils.isEmpty(key)) {
			throw new IllegalArgumentException("key不能为空" + key);
		}
		this.key = key;
	}

	public AjaxMessage getPayload() {
		return payload;
	}

	public void setPayload(AjaxMessage payload) {
		if (payload == null) {
			throw new IllegalArgumentException("payload不能为空");
		}
		this.payload = payload;
	}

	/**
	 * 得到错误key
	 * 
	 * @return
	 */
	private static String getErrorKey() {
		return "error/" + UUID.randomUUID().toString();
	}

	public String toJsonString() {
		return JSON.toJSONString(this);
	}
}
